/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-02-17
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-03-15
 * @Description: 
 */
import 'package:chat_client/models/group_model.dart';
import 'package:chat_client/repositories/hive_repository.dart';
import 'package:hive/hive.dart';

/// 群聊信息本地储存
class GroupRepository {
  // 单例
  GroupRepository._internal();
  static final GroupRepository _instance = GroupRepository._internal();
  static GroupRepository get instance => _instance;
  // hive 实例
  static final _hive = HiveService.instance;
  late final Box<Group> _groupBox;
  late final Box<Member> _memberBox;

  // 打开数据库
  Future<void> init() async {
    _groupBox = await _hive.openBox<Group>('group');
    _memberBox = await _hive.openBox<Member>('groupMember');
  }

  // 储存单个群聊
  Future<void> setGroup(Group group) async {
    await _groupBox.put(group.groupId, group);
  }

  // 获取本地群聊列表
  List<Group> getGroupList() {
    return _groupBox.values.toList();
  }

  // 批量储存群成员
  Future<void> setGroupMembers(List<Member> memberList, String groupId,
      {bool invite = false}) async {
    for (var m in memberList) {
      await _memberBox.put(m.memberId, m);
    }

    // 更新群聊
    if (!invite) return;
    final members = memberList.map((m) => m.memberId).toList();
    updateGroup(delete: true, members: members, groupId: groupId);
  }

  // 获String key
  Group? getGroup(String key) {
    return _groupBox.get(key);
  }

  // 获取单个群聊的所有群成员
  List<Member> getMembers(List<String> members) {
    return members
        .map((memberId) => _memberBox.get(memberId)) // 转换ID为Member对象
        .where((message) => message != null) // 过滤掉null值
        .cast<Member>() // 类型转换保障
        .toList(); // 转换为结果列表
  }

  // 批量删除群成员
  Future<void> deleteMembers(List<String> memberIds, String groupId) async {
    for (var id in memberIds) {
      await _memberBox.delete(id);
    }

    // 更新群聊
    updateGroup(delete: true, members: memberIds, groupId: groupId);
  }

  // 修改群聊中的成员列表(默认删除)
  Future<void> updateGroup({
    required List<String> members,
    required String groupId,
    bool delete = true,
  }) async {
    final group = getGroup(groupId);
    if (group == null) throw Exception('群聊数据丢失，请尝试重新登录');
    if (delete) {
      final memberIdSet = members.toSet();
      final filteredList = group.memberList
          .where((id) => !memberIdSet.contains(id)) // 排除 members 中的元素
          .toList();
      group.copyWith(memberList: filteredList);
    } else {
      // 过滤掉已存在的成员
      final existingMemberSet = group.memberList.toSet();
      final uniqueNewMembers = members
          .where((id) => !existingMemberSet.contains(id)) // 排除已存在的成员
          .toList();

      // 更新群组成员列表
      final updatedMemberList = [...group.memberList, ...uniqueNewMembers];
      group.copyWith(memberList: updatedMemberList);
    }
  }

  // 删除群组并删除所有群成员
  Future<void> deleteGroupMembers(String groupId) async {
    final group = getGroup(groupId);
    if (group == null) throw Exception('群聊数据丢失，请尝试重新登录');

    // 删除群成员
    for (var memberId in group.memberList) {
      await _memberBox.delete(memberId);
    }
    // 删除群组
    await _groupBox.delete(groupId);
  }
}
